<template>
    <div class="breakball11">
        <div id="breakBall" width="900" height="600"></div>
        <div class="container" v-if="gameOver">
            <div class="dialog">
                <p class="once-again">本轮分数：{{score}}分</p>
                <p class="once-again">真好玩！</p>
                <p class="once-again">再来一次~~</p>
                <el-button class="once-again-btn" @click="init">开始</el-button>
                <el-button type="danger" @click="back_home">退出</el-button>
            </div>
        </div>
    </div>

</template>

<script>
    import Common from '../components/common'
    import * as PIXI from 'pixi.js'
    const axios=require('axios')
    const randomColour=[
        "#d41313",
        "#e3b200",
        "#e35b00",
        "#00d254",
        "#002ed2",
        "#87c2b9",
        "#703caa",
        "#FFDC35",
        "#93FF93",
        "#d0d0d0"
    ];

    export default {
        name: "test",
        data(){
            return{
                username:'',
                score:0,
                ctx: null,
                crushBalls: [],
                panel:'',
                ball: {
                    x:0,
                    y:0,
                },
                Target:'',
                breaks:[],
                gameOver:false
            }
        },
        mounted(){
            let _this=this;
            _this.username=this.$cookies.get("username")
            _this.app=new PIXI.Application({
                width:900,
                height:600,
                transparent: true,
                antialias: true,
                autoDensity: true,
            })
            var container=document.getElementById("breakBall")
            container.appendChild(_this.app.view)
            _this.app.stage.interactive=true
            _this.drawAll();
            _this.init();
            document.onkeydown = function(e) {
                let key = window.event.keyCode;
                if (key === 37  || event.keyCode==65) {
                    // 左键 或A
                    _this.panel.vx=-7;
                } else if (key === 39  || event.keyCode==68) {
                    // 右键 或D
                    _this.panel.vx = 7;
                }
            },

                document.onkeyup=function (e) {
                    _this.panel.vx=0
                };

            // (function animloop() {
            //     if (!_this.gameOver) {
            //         _this.movePannel();
            //         _this.moveBall();
            //         _this.moveTarget();
            //         _this.drawAll();
            //     }
            //     else{
            //         _this.drawCrushBreaks();
            //     }
            //     window.requestAnimationFrame(animloop);
            // })();
            _this.move_start();

        },

        methods:{
            init() {
                let _this = this;
                _this.gameOver = false;
                _this.ball.x=this.app.renderer.screen.width  / 2;
                _this.ball.y=this.app.renderer.screen.height  / 2;
                //_this.ball.position.set(this.app.renderer.screen.width/2,this.app.renderer.screen.height/2)
                //this.Target.x = this.clientWidth / 2 - this.panel.width / 2;
                this.crushBalls = [];
                this.score = 0;
            },
            move_start(){
                this.movePannel();
                this.moveBall();
                this.moveTarget();
            },
            back_home(){
                this.$router.push("/home");
            },
            drawTarget(){
                this.Target=new PIXI.Graphics();
                this.Target.width=300
                this.Target.height=8
                //console.log(this.panel.width)
                // this.panel.x=this.clientWidth/2-250
                // this.panel.y=this.clientHeight/2-4
                //console.log(this.clientHeight)
                this.Target.position.set(this.app.renderer.screen.width / 2-this.Target.width, 10);
                console.log(this.Target.position.y)
                this.Target.lineStyle(4, 0X008B8B, 1);
                this.Target.beginFill(0X008B8B);
                this.Target.drawRoundedRect(0,0,300,8,5);  //注意这里，x,y参数会自动左panel-x,右panel+x
                this.Target.endFill();
                this.Target.vx=3
                this.Target.vstop=0
                this.Target.interactive=true
                //console.log(this.panel)
                this.app.stage.addChild(this.Target)
                //this.drawRoundRect(this.Target.x,this.Target.y,this.Target.width,this.Target.height,2,"#008b8b");

            },
            moveTarget(){
                this.app.ticker.add(() =>{
                    this.Target.x += this.Target.vx;
                    if (this.Target.x<0){
                        this.Target.vx=-this.Target.vx;
                    }
                    else if(this.Target.x>this.app.renderer.screen.width-this.Target.width){
                        this.Target.vx=-this.Target.vx;
                    }
                })

            },

            drawPanel(){
                this.panel=new PIXI.Graphics();
                this.panel.width=100
                this.panel.height=8
                //console.log(this.panel.width)
                // this.panel.x=this.clientWidth/2-250
                // this.panel.y=this.clientHeight/2-4
                //console.log(this.clientHeight)
                this.panel.position.set(this.app.renderer.screen.width / 2-100, 590);
                console.log(this.panel.position.y)
                this.panel.lineStyle(4, 0XF8F8FF, 1);
                this.panel.beginFill(0XF8F8FF);
                this.panel.drawRoundedRect(0,0,100,8,5);  //注意这里，x,y参数会自动左panel-x,右panel+x
                this.panel.endFill();
                this.panel.vx=0
                this.panel.vstop=0
                this.panel.interactive=true
                //console.log(this.panel)
                this.app.stage.addChild(this.panel)
                //this.drawRoundRect(this.pannel.x, this.pannel.y, this.pannel.width, this.pannel.height, 5,"#FFF");
            },


            movePannel(){
                if(this.gameOver==false){
                    this.app.ticker.add(() =>{
                        this.panel.x+=this.panel.vx
                        //console.log(this.panel.x)
                        if (this.panel.x<=0){
                            this.panel.x=0;
                        }
                        else if(this.panel.x>=this.app.renderer.screen.width-this.panel.width){
                            this.panel.x=this.app.renderer.screen.width-this.panel.width;
                        }
                    })
                }
                else {
                    return;
                }
            },

            drawBall() {
                this.ball=new PIXI.Graphics();
                // this.ball.y = this.app.renderer.screen.height / 2;
                // this.ball.x = this.app.renderer.screen.width  / 2;
                this.ball.radius=8;
                this.ball.beginFill(0X008B8B);
                this.ball.drawCircle(0,0,this.ball.radius);
                this.ball.endFill();
                this.ball.vx=[-1,1][Math.floor(Math.random() * 2)]*4;
                this.ball.vy=[-1,1][Math.floor(Math.random() * 2)]*4;
                this.app.stage.addChild(this.ball)
            },
            moveBall() {
                this.app.ticker.add(() =>{
                    if(this.gameOver==false){
                        this.ball.x += this.ball.vx;
                        this.ball.y += this.ball.vy;
                        // this.breaksHandle();
                        this.edgeHandle();
                    }
                    else {
                        return;
                    }
                })

            },
            drawAll() {
                // this.ctx.clearRect(0, 0, this.clientWidth, this.clientHeight);
                this.drawPanel();
                this.drawBall();
                this.drawTarget();
                //this.drawTarget();
                this.drawScore();
            },

            edgeHandle() {
                if (this.ball.x - this.ball.radius <= 0 || this.ball.x + this.ball.radius >= 900) {
                    this.ball.vx = -this.ball.vx;
                }
                if(this.ball.x>=this.Target.x
                    && this.ball.x<=this.Target.x+this.Target.width
                    && (this.ball.y - this.ball.radius <= this.Target.y+this.Target.height))
                {
                    this.ball.vy=-this.ball.vy;
                    this.ball.vx=-this.ball.vx
                    this.score+=2;
                    this.Target.vx+=0.3;
                    this.Target.width-=0.5
                }
                if (this.ball.y - this.ball.radius <= 0) {
                    this.ball.vy = -this.ball.vy;
                }
                if(this.ball.x-this.panel.x>=0
                    && this.ball.x<=this.panel.x+this.panel.width
                    && this.ball.y + this.ball.radius >= this.app.renderer.screen.height - this.panel.height){
                    this.ball.vy=-this.ball.vy;
                    this.score+=1;
                }
                else if((this.ball.x < this.panel.x
                    || this.ball.x > this.panel.x + this.panel.width) &&
                    this.ball.y + this.ball.radius >= this.app.renderer.screen.height){
                    this.gameOver=true;
                    let data=new URLSearchParams()
                    data.append('username',this.username)
                    data.append('ball',this.score)
                    console.log(this.score)
                    axios.post('/user/updateball',data).then(res =>{
                        console.log(res)
                    })
                }
                this.getCurshBreaks();
            },

            drawScore(){
                // this.ctx.beginPath();
                // this.ctx.font="14px Arial";
                // this.ctx.fillStyle = "#FFF";
                // this.ctx.fillText("分数："+this.score,10,this.clientHeight-14);
                // this.ctx.closePath();
                let style = new PIXI.TextStyle({
                    fontFamily: "Arial",
                    fontSize: 15,
                    fill: "white",
                    stroke: '#ff3300',
                    strokeThickness: 4,
                    dropShadow: true,
                    dropShadowColor: "#000000",
                    dropShadowBlur: 4,
                    dropShadowAngle: Math.PI / 6,
                    dropShadowDistance: 6,
                });
                this.app.ticker.add(() =>{
                    let message=new PIXI.Text("分数："+this.score,style);
                    message.position.set(20,560);
                    this.app.stage.addChild(message);
                })

            },

            getRandomArbitrary(min, max) {
                return Math.random()*(max-min)+min;
            },
            getRandomColor(){
                return randomColour[Math.floor(Math.random() * randomColour.length)];
            },

            getCurshBreaks() {
                let _this = this;
                for (let i = 0; i < 10+_this.score*5; i++) {
                    this.crushBalls.push({
                        x: 5,
                        y: 5,
                        dx: _this.getRandomArbitrary(-6, 6),
                        dy: _this.getRandomArbitrary(-6, 6),
                        r: _this.getRandomArbitrary(1, 4),
                        color: _this.getRandomColor()
                    });
                }
            },

            drawCrushBreaks() {
                this.ctx.clearRect(0, 0, this.clientWidth, this.clientHeight);
                this.crushBalls.forEach(item => {
                    this.ctx.beginPath();
                    this.ctx.arc(item.x, item.y, item.r, 0, 2 * Math.PI);
                    this.ctx.fillStyle = item.color;
                    this.ctx.fill();
                    this.ctx.closePath();
                    item.x += item.dx;
                    item.y += item.dy;
                    if (
                        // 碰到左右墙壁
                        item.x - item.r < 0 ||
                        item.x + item.r > this.clientWidth
                    ) {
                        item.dx = -item.dx;
                    }
                    if (
                        // 碰到上下墙壁
                        item.y - item.r < 0 ||
                        item.y + item.r > this.clientHeight
                    ) {
                        item.dy = -item.dy;
                    }
                });
            },

        }

    }
</script>

<style lang="scss" scoped>
    #breakBall {
        background-image: url("../assets/Game-background.jpg");
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        position: absolute;
    }
    .container {
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        width: 900px;
        height: 600px;
        left: 0;
        background-color: rgba(0, 0, 0, 0.3);
        text-align: center;
        font-size: 0;
        white-space: nowrap;
        overflow: auto;
    }
    .container:after {
        content: "";
        display: inline-block;
        height: 100%;
        vertical-align: middle;
    }
    .dialog {
        width: 400px;
        height: 300px;
        background: rgba(255, 255, 255, 0.5);
        box-shadow: 3px 3px 6px 3px rgba(0, 0, 0, 0.3);
        display: inline-block;
        vertical-align: middle;
        text-align: left;
        font-size: 28px;
        color: #fff;
        font-weight: 600;
        border-radius: 10px;
        white-space: normal;
        text-align: center;
        .once-again-btn {
            background: #1f9a9a;
            border: none;
            color: #fff;
        }
    }
</style>